package com.frxuexi.cart.view

import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.cart.viewmodel.CartViewModel
import com.frxuexi.cart.R
import com.frxuexi.cart.adapter.CartAdapter
import com.frxuexi.cart.databinding.FragmentCartBinding
import com.frxuexi.lib_base.entity.CartBeanList
import com.frxuexi.lib_base.mvvm.BaseFragment
import com.frxuexi.lib_base.room.ProductEntity
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    val cartAdapter by lazy { CartAdapter() }
    var sum = 0.0//原总价
    var sum2 = 0.0//减券后总价
    var position = -1
    var coupon = 0.0
    var couponId = 0
    override fun initData() {
        vm.cartError.observe(this) {
            ToastUtils.showLong(it)

        }

        vm.cartData.observe(this) {
            cartAdapter.apply {
                data.clear()
                addData(it.list)
                notifyDataSetChanged()
            }

            binding.cartNum.setText("购物车（${it.limit}）")
        }

        vm.upadteCartData.observe(this) {
            cartAdapter.notifyItemChanged(position)
        }

        vm.deleteCartData.observe(this) {
            vm.getCarts(1)
            binding.cbAll.isChecked = false
            binding.cbAll.setText("全选（0）")
            binding.amountCou.setText("全选（0）")
            binding.amountAll.setText("合计：￥0.0")
        }

        vm.myCouponData.observe(this) {
            //已领取的最大优惠券金额
            val item = it.list?.sortedByDescending { it.money.toDouble() }?.get(0)
            coupon = item?.money?.toDouble()?:0.0
            couponId=item?.id?:-1
        }

    }

    override fun initView() {
        binding.rvCar.apply {
            adapter = cartAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }


        //获取我的优惠券
        vm.getMyCoupon()

        binding.cartMan.apply {
            setOnClickListener {
                if (text.toString() == "管理") {
                    setText("完成")
                    binding.cartDelLove.visibility = View.VISIBLE
                    binding.cartJie.visibility = View.GONE
                } else {
                    setText("管理")
                    binding.cartDelLove.visibility = View.GONE
                    binding.cartJie.visibility = View.VISIBLE
                }
            }
        }

//        左滑删除
        ItemTouchHelper(object :SimpleCallback(ItemTouchHelper.LEFT, LEFT){
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val pos = viewHolder.adapterPosition
                //删除
                vm.deleteCart(listOf(cartAdapter.data.get(pos).id))
            }
        }).attachToRecyclerView(binding.rvCar)


//        全选反选
        binding.cbAll.apply {
            setOnClickListener {
//                遍历，把所有的数据选中状态和cbAll保存一致
                cartAdapter.data.forEach { it.isCheck = isChecked }
                cartAdapter.notifyDataSetChanged()
//                选中的商品个数赋值
                setText("全选（${if (isChecked) cartAdapter.data.size else 0}）")
                sum()
            }
        }

        cartAdapter.addChildClickViewIds(R.id.car_check_box, R.id.car_sub, R.id.car_add)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            val bean = cartAdapter.data.get(position)
            this.position = position
            when (view.id) {
//                item的checkbox联动全选的状态
                R.id.car_check_box -> {
                    //把点击的这个商品的选中状态反过来
                    bean.isCheck = !bean.isCheck
                    //局部刷新
                    cartAdapter.notifyItemChanged(position)
                    //全选的状态根据每个item的状态改变
                    binding.cbAll.isChecked = cartAdapter.data.all { it.isCheck }
                    //                选中的商品个数赋值
                    binding.cbAll.setText("全选（${cartAdapter.data.filter { it.isCheck }.count()}）")
                }

                R.id.car_add -> {
                    var num = bean.cartNum + 1
                    if (num <= bean.stock) {
                        vm.upadteCart(bean.id, num)
                        bean.cartNum = num
                    } else {
                        ToastUtils.showLong("不能超过库存量")
                    }
                }

                R.id.car_sub -> {
                    var num = bean.cartNum - 1
                    if (num <= 0) {
                        ToastUtils.showLong("购买数量不能小于1")
                    } else {
                        vm.upadteCart(bean.id, num)
                        bean.cartNum = num
                    }
                }
            }
            sum()
        }

        binding.cartDelete.setOnClickListener {
            //删除
            vm.deleteCart(cartAdapter.data.filter { it.isCheck }.map { it.id })
        }

        binding.cartLove.setOnClickListener {
            cartAdapter.data.filter { it.isCheck }.forEach { bean ->
                val entity = ProductEntity(
                    bean.productId,
                    bean!!.image,
                    bean!!.storeName,
                    bean!!.price,
                    ""
                )
                vm.addPro(
                    entity
                )
            }
        }

        binding.buyNow.setOnClickListener {
            val beanList = CartBeanList(cartAdapter.data.filter { it.isCheck })
            ARouter.getInstance().build("/cart/OrderConfirmActivity")
                .withSerializable("order", beanList).withDouble("cou", coupon)
                .withInt("couId",couponId)
                .withDouble("yuan",sum)
                .withDouble("sum",sum2)
                .navigation()
        }

    }

    //不需要优惠券的总价
    /*fun sum(){
        sum=cartAdapter.data.filter { it.isCheck }.sumOf { it.cartNum*it.price.toDouble() }
        binding.amountAll.setText("合计：￥${sum}")
    }*/

    //计算需要优化券的总价
    fun sum() {
//        计算原总金额
        sum = cartAdapter.data.filter { it.isCheck }.sumOf { it.cartNum * it.price.toDouble() }
//        总金额大于优惠券
        if (sum >= coupon) {
//最后总结=原总金额-优惠券
            sum2 = sum - coupon
            binding.amountCou.setText("优惠：￥${coupon}")
        } else {
            sum2 = sum
        }

        binding.amountAll.setText("合计：￥${sum2}")
    }

    override fun onResume() {
        super.onResume()
        vm.getCarts(1)
        binding.cbAll.isChecked = false
        binding.cbAll.setText("全选（0）")
        binding.amountCou.setText("全选（0）")
        binding.amountAll.setText("合计：￥0.0")
        binding.amountCou.setText("优惠：￥0.0")
    }

}